package com.steven.ourcontest.report.view

import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.activity.viewModels
import com.bumptech.glide.Glide
import com.daimajia.numberprogressbar.NumberProgressBar
import com.steven.ourcontest.R
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.base.DialogBuilder
import com.steven.ourcontest.report.viewmodel.ReportViewModel
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.net.FileRequestBody
import com.steven.ourcontest.net.RetrofitCallback
import com.steven.ourcontest.utils.DensityUtil
import com.steven.ourcontest.utils.ScreenUtils
import com.steven.ourcontest.utils.openAlbum
import com.steven.ourcontest.utils.toast
import id.zelory.compressor.Compressor
import kotlinx.android.synthetic.main.activity_report.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class ReportActivity : BaseActivity() {
    private var uid: Long = 0
    private val picPathArray = ArrayList<String>()
    private val reportViewModel: ReportViewModel by viewModels()
    override fun getStatusBarColor(): Int {
        return R.color.white
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getViewId(): Int? {
        return R.layout.activity_report
    }

    override fun initView() {
        uid = intent.getLongExtra("uid", 0)
        if (uid == 0L) {
            finish()
            return
        }
        val layoutParams = iv_add_picture?.layoutParams
        DensityUtil.dp2px(this, 24f).let { dp ->
            layoutParams?.width = (ScreenUtils.getScreenWidth(this) - dp) / 3 - dp / 3
            layoutParams?.height = layoutParams?.width
        }
        iv_add_picture?.layoutParams = layoutParams
        iv_add_picture?.setOnClickListener {
            openAlbum(this)
        }
        tv_confirm?.setOnClickListener {
            val content = et_content?.text
            if (!checkText(content)) {
                return@setOnClickListener
            }
            val dialog = DialogBuilder(this)
                .setCancelable(false)
                .build(R.layout.dialog_upload)
            dialog.show()
            val progressView = dialog.findViewById<NumberProgressBar>(R.id.progress)
            GlobalScope.launch(Dispatchers.Default) {
                val body = MultipartBody.Builder()
                picPathArray.forEach {
                    val file = File(it)
                    val resFile = Compressor.compress(this@ReportActivity, file)
                    val fileRQ = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        resFile
                    )
                    body.addFormDataPart("images", resFile.name, fileRQ)
                }
                body.addFormDataPart("content", content.toString()).addFormDataPart("targetUid", uid.toString())
                val realBody = FileRequestBody(body.build(), object : RetrofitCallback<EmptyResponse>() {
                    override fun onLoading(total: Long, progress: Long) {
                        GlobalScope.launch(Dispatchers.Main) {
                            super.onLoading(total, progress)
                            progressView.progress =
                                ((progress / total.toFloat()) * 100).toInt()
                            if (total == progress) {
                                dialog.dismiss()
                            }
                        }
                    }
                })
                reportViewModel.addReport(realBody) {
                    toast("上传成功，我们将尽快处理您的反馈！")
                    finish()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> {
                val cursor: Cursor? = data?.data?.let {
                    contentResolver?.query(
                        it,
                        arrayOf(MediaStore.Images.Media.DATA),
                        null,
                        null,
                        null
                    )
                }
                cursor?.moveToFirst()
                val path = cursor?.getString(
                    cursor.getColumnIndex(
                        MediaStore.Images.Media.DATA
                    )
                ) ?: ""
                cursor?.close()
                try {
                    if (path == "") {
                        throw Exception("file path is error")
                    }
                    picPathArray.add(path)
                    val imageView = ImageView(this)
                    val layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    DensityUtil.dp2px(this, 24f).let { dp ->
                        layoutParams.width = (ScreenUtils.getScreenWidth(this) - dp) / 3 - dp / 3
                        layoutParams.height = layoutParams.width
                        layoutParams.marginStart = dp / 6
                        layoutParams.marginEnd = dp / 6
                        layoutParams.topMargin = dp / 6
                        layoutParams.bottomMargin = dp / 6
                    }
                    imageView.layoutParams = layoutParams
                    imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                    val viewAt = flex_container.indexOfChild(iv_add_picture)
                    flex_container?.addView(imageView, viewAt)
                    Glide.with(this)
                        .load(path)
                        .placeholder(R.drawable.ic_placeholder)
                        .dontAnimate()
                        .error(R.drawable.aio_image_fail)
                        .into(imageView)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun checkText(text: Editable?): Boolean {
        if (text.isNullOrEmpty()) {
            toast("文本不能为空")
            return false
        }
        return true
    }
}